package com.moneywelcome.riskassembly.apiImpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moneywelcome.api.RiskApi;
import com.moneywelcome.dto.RiskResult;
import com.moneywelcome.exceptions.MwcArgsException;
import com.moneywelcome.results.Result;
import com.moneywelcome.results.StatusCode;
import com.moneywelcome.riskassembly.model.EngineModel;
import com.moneywelcome.riskassembly.model.RiskRecord;
import com.moneywelcome.riskassembly.service.EngineModelService;
import com.moneywelcome.riskassembly.service.RiskRecordService;
import com.moneywelcome.riskassembly.util.RiskResultUtil;
import com.moneywelcome.vo.EventRequest;
import com.moneywelcome.vo.RiskVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j

public class RiskApiImpl implements RiskApi {

    @Autowired
    private EngineModelService ems;
    @Autowired
    private RiskRecordService rrs;
    @Override
    public Result<RiskResult> uoloadInfo(RiskVo riskVo) {
        String url="http://192.168.120.19:6581/services/v1/upload";
        EngineModel model = ems.getOne(new QueryWrapper<EngineModel>().eq("LABEL", riskVo.getModelName()));
        if(null==model) throw new MwcArgsException("模型不存在", StatusCode.Error);
        log.info("模型{}",model);
        //请求json
        JSONObject reqJson = riskVo.getJsonInfo();
        String eventId = reqJson.get("eventId").toString();
        //事件请求对象
        EventRequest eventRequest = new EventRequest();
        eventRequest.setGuid(model.getGuid());
        eventRequest.setReqId(eventId);
        eventRequest.setJsonInfo(riskVo.getJsonInfo());
        String jsonStr = JSONUtil.toJsonStr(eventRequest);
        //向radar发送请求
        String result2 = HttpRequest.post(url)
                .body(jsonStr)
                .execute().body();
        log.info("风控结果{}",result2);
        RiskResult riskResult = RiskResultUtil.parseResult(result2);
        if("reject".equals(riskResult.getActivations().getRisk())){
            if(null!=rrs.getOne(new QueryWrapper<RiskRecord>().eq("event_id",eventId))) throw new MwcArgsException("记录已存在",StatusCode.Error);
            log.info("触发风控{}",riskResult);
            //保存风控记录
            RiskRecord riskRecord = new RiskRecord();
            riskRecord.setUserId(reqJson.getString("userId"));
            riskRecord.setEventId(eventId);
            riskRecord.setTriggeringTime(DateUtil.now());
            riskRecord.setRiskGrade(riskResult.getActivations().getScore());
            if(!rrs.save(riskRecord)) throw new MwcArgsException("记录保存失败",StatusCode.Error);
        }
        return Result.success(riskResult);
    }
}
